﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ADail;
using Asterisk.NET.Manager;
using Asterisk.NET.Manager.Action;
using Asterisk.NET.Manager.Response;

namespace ADial

{
    public class CallManager
    {
        private ManagerConnection _managerConnection = null;
        public ManagerConnection ManagerConnection
        {
            set
            {
                _managerConnection = value;
            }
            get
            {
                return _managerConnection;
            }
        }

        private ArrayList _callHandlers = null;
        public ArrayList CallHandlers
        {
            set
            {
                _callHandlers = value;
            }
            get
            {
                return _callHandlers;
            }
        }

        public void dial(string number)
        {
            foreach (ICallHandler handler in _callHandlers)
            {
                if(handler.matches(number))
                {
                    string parsedNumber = handler.extract(number);
                    
                    foreach (object action in handler.Actions)
                    {
                        ManagerAction sendAction = null;
                        if(action is ManagerAction)
                        {
                            sendAction = (ManagerAction) action;
                        }
                        else if(action is PropertySetterAction)
                        {
                            ((PropertySetterAction)action).setNumber(parsedNumber);
                            sendAction = ((PropertySetterAction) action).Action;
                        }
                        //MessageBox.Show(sendAction.GetType().ToString());
                        if (!_managerConnection.IsConnected())
                        {
                            _managerConnection.Login();
                        }
                        if(sendAction is OriginateAction)
                        {
//                            ((OriginateAction)sendAction).SetVariable("callnumber", parsedNumber);
                            
                        }
                        
                        ManagerResponse response = _managerConnection.SendAction(sendAction, 3000);
                        Console.Out.WriteLine("Response: " + response.ToString());
                    }
                }
            }   
        }

    }
}
